/*
 * @Author: your name
 * @Date: 2020-08-09 15:08:20
 * @LastEditTime: 2020-08-09 15:49:03
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \day01\demo03\main.go
 */
package main

import (
	"fmt"
	"log"
	"net/http"
)

// import "fmt"

// // 装饰器练习

// func f1() {
// 	fmt.Println("f1 函数")
// }

// func f2(f func()) {
// 	fmt.Println("执行之前")
// 	f()
// 	fmt.Println("执行之后")

// }

// func main() {
// 	fmt.Printf("%T\n", f1)
// 	f2(f1)
// }

// =========================================================
// 装饰器的运用

// func homePage(w http.ResponseWriter, r *http.Request) {
// 	fmt.Println("Hit: home page")
// 	fmt.Println(w, "welcome to the home")
// }

// func handleRequests() {
// 	http.HandleFunc("/", homePage)
// 	log.Fatal(http.ListenAndServe(":8001", nil))
// }

// func main() {
// 	handleRequests()
// }

// =========================================================
// 装饰器的运用 ... 升级版.

func isAuthorized(f func(http.ResponseWriter, *http.Request)) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Println("checking to see if author")

		if val, ok := r.Header["Authorized"]; ok {
			fmt.Println(val)
			if val[0] == "true" {
				fmt.Println("header is set")
				f(w, r)
			}
		} else {
			fmt.Println("not authorized")
		}
	})

}

func homePage(w http.ResponseWriter, r *http.Request) {
	fmt.Println("Hit : welcome home page ...........")
}

func handleRequests() {
	http.Handle("/", isAuthorized(homePage))
	log.Fatal(http.ListenAndServe(":8001", nil))
}

func main() {
	handleRequests()
}
